package toOffer;

/**
 * @author YuanAo
 * @date 2024/6/26 16:48
 * @description 训练计划III
 */

import java.util.Objects;

/**
 * 题目：
 * 给定一个头节点为 head 的单链表用于记录一系列核心肌群训练编号，请将该系列训练编号 倒序 记录于链表并返回。
 * 示例 1：
 * 输入：head = [1,2,3,4,5]
 * 输出：[5,4,3,2,1]
 * <p>
 * 示例 2：
 * 输入：head = [1,2]
 * 输出：[2,1]
 * <p>
 * 示例 3：
 * 输入：head = []
 * 输出：[]
 */
public class LCR141 {
    public static void main(String[] args) {
        int[] ints = {1, 2, 3, 4, 5};
        // 初始化
        ListNode listNode = new ListNode();
        for (int i = ints.length - 1; i >= 0; i--) {
            if (i == ints.length - 1) {
                listNode = new ListNode(ints[i]);
            } else {
                listNode = new ListNode(ints[i], listNode);
            }
        }

        ListNode ln = trainningPlan(listNode);
        while (Objects.nonNull(ln)) {
            System.out.print(ln.getVal() + " ");
            ln = ln.next;
        }
    }

    /**
     * 思路：原地反转
     * @param head
     * @return
     */
    public static ListNode trainningPlan(ListNode head) {
        if (head == null) return head;
        ListNode preNode = null;
        ListNode tempNode;
        while (head != null){
            tempNode = head.next;
            head.next = preNode;
            preNode = head;
            head = tempNode;
        }

        return preNode;
    }

    public static class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public ListNode getNext() {
            return next;
        }

        public void setNext(ListNode next) {
            this.next = next;
        }
    }
}
